﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Windows.Forms;
using DBCodeBuilder.Core.Classes;

namespace DBCodeBuilder
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();

            Dictionary<string, string> connections = new Dictionary<string, string> {{"", ""}};

            for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
                connections.Add(ConfigurationManager.ConnectionStrings[i].Name,
                    ConfigurationManager.ConnectionStrings[i].ConnectionString);

            cmbConnection.DisplayMember = "Key";
            cmbConnection.ValueMember = "Value";
            cmbConnection.DataSource = new BindingSource(connections, null);

            cmbConnection.SelectedIndex = 1;
        }

        #region Events

        private void btnClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (cmbConnection.SelectedIndex == 0 || String.IsNullOrEmpty(txtUsername.Text) || String.IsNullOrEmpty(txtPass.Text))
            {
                MessageBox.Show("Not all connection informations have been specified.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            lblBadLogin.Visible = false;
            try
            {
                DbProvider.Init(txtUsername.Text, txtPass.Text, cmbConnection.SelectedValue.ToString());
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message, "Bad connection string", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (DbProvider.TestConnection())
            {
                SessionInfo.Instance.UserName = txtUsername.Text;
                Visible = false;

                (new Main_Designer()).ShowDialog();

                Application.Exit();
            }
            else
                lblBadLogin.Visible = true;
        }

        private void cmbConnection_SelectedIndexChanged(object sender, EventArgs e)
        {
            var conStr = cmbConnection.SelectedValue.ToString();

            if (cmbConnection.SelectedIndex == 0)
                return;

            if (!conStr.Substring(0, 8).Contains("User Id"))
                return;

            string[] userAndPass = conStr.Split(new[] {';'}, 3);
            string username = userAndPass[0].Split('=')[1];
            string pass = userAndPass[1].Split('=')[1];
            txtUsername.Text = username != "{0}" ? username : "";
            txtPass.Text = pass != "{1}" ? pass : "";

            txtUsername.Enabled = username == "{0}";
            txtPass.Enabled = pass == "{1}";
        }

        #endregion
    }
}